package com.zzttwl.locktcp.start;

import org.apache.ibatis.io.Resources;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.Reader;
import java.util.Properties;
import java.util.Scanner;
import java.util.regex.Pattern;

public class PortService {
	private static Logger logger = Logger.getLogger(PortService.class);

	/**
	 * 从配置文件获取端口号
	 * @return int 端口号
	 * @author xubaisen
	 */
	public int getIniPort() {
		int port = 8080;
		Properties prop =  new  Properties();    
		Reader reader;
		try {
			reader = Resources.getResourceAsReader("port.properties");
			prop.load(reader);
		} catch (IOException e2) {
			e2.printStackTrace();
		}
        String regEx = "^\\d{1,5}$";
        Pattern pattern = Pattern.compile(regEx);
        String str = prop.getProperty("port");
        if (pattern.matcher(str).matches()) {
        	port = Integer.parseInt(str);
        	return port;
        }
        else {
			logger.error("配置文件中的端口号不正确！请检查配置文件。或尝试手动输入端口号");
			logger.info("是否要手动输入端口号 ? Y/N");
        	Scanner sc = new Scanner(System.in);
        	String s = sc.nextLine();
        	if(s.equalsIgnoreCase("Y")) {
        		port = getInputPort();
        	}else if(s.equalsIgnoreCase("N")){
				logger.warn("系统将启用默认端口号 8080");
        	}else {
				logger.error("输入有误，5秒后将使用默认端口号  8080");
        	    try {
				Thread.sleep(5000);
			    } catch (InterruptedException e) {
				    e.printStackTrace();
			    }
        	}
        	sc.close();
        	return port;
        }
	}
	
	/**
	 * 从控制台输入获取端口号
	 * @return int 端口号
	 * @author zhangxl
	 */
	public int getInputPort() {
		Scanner sc = new Scanner(System.in);
		String regEx = "^\\d{1,5}$";
		Pattern pattern = Pattern.compile(regEx);
		String str;
		System.out.println("请输入端口号：");
		while (true) {
			str = sc.nextLine();
			if (pattern.matcher(str).matches()) {
				sc.close();
				break;
			} else {
				logger.warn("输入不合法，请输入服务器要绑定的正确的端口号");
			}
		}
		int port = Integer.parseInt(str);
		return port;
	}
}
